﻿namespace KinonekoSoftware.Studio.Enums
{
    /// <summary>
    /// <see cref="EnumSingleSelect{T}"/> 类型用于实现对某个
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public sealed class EnumSingleSelect<T> : EnumChoice where T : struct, Enum
    {
        private readonly EnumMaster<T>  _master;
        private readonly int            _mask;
        private readonly string         _propertyName;
        private readonly Action<T>      _handler;
        private readonly Action<string> _callback;
        private          int            _oldValue;

        public EnumSingleSelect(T value, string propertyName, Action<string> callback, EnumMaster<T> master, Action<T> handler)
        {
            _master       = master ?? throw new ArgumentNullException(nameof(master));
            _callback     = callback;
            _handler      = handler;
            _mask         = EnumStatic.Cast(value);
            _propertyName = propertyName;
        }
        

        internal override void RaiseUpdated()
        {

            //
            //
            _callback?.Invoke(_propertyName);
        }

        public bool Value
        {
            get => (_master.value & _mask) == _mask;
            set
            {
                if (value)
                {
                    _oldValue     = _master.value;
                    _master.value = _mask;
                }
                else
                {
                    _master.value = _oldValue;
                }

                //
                //
                _master.NotifyChanges();

                //
                //
                _callback?.Invoke(_propertyName);
                _handler?.Invoke(_master.Value);
            }
        }
    }
}